/*
 * Copyright (C) 2015 andrea
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package meteocal.boundary;

import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import meteocal.entity.Users;
import meteocal.entityManager.UserManager;

/**
 *
 * @author andrea
 */
@Named(value = "registrationBean")
@RequestScoped
public class RegistrationBean {
    
    @EJB
    private UserManager um;
    
    private Users user;
    
    private Date userBirthday;
    
    public Users getUser(){
        if(this.user == null){
            this.user = new Users();
        }
        return this.user;
    }
    
    public void setUser(Users user){
        this.user = user;
    }
    
    public String register(){
        if(um.exist(user)){
            sendMessage("This email is already used!");
            return null;
        }
        convertDateToCalendar();
        um.save(user);
        this.userBirthday = null;
        return "/index?faces-redirect=true";
    }

    private void sendMessage(String msg) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", msg);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public void convertDateToCalendar(){
        Calendar birth = Calendar.getInstance();
        if(this.userBirthday != null){
        birth.setTime(this.getUserBirthday());
        this.user.setBirthday(birth);
        }
    }

    /**
     * @param userBirthday the userBirthday to set
     */
    public void setUserBirthday(Date userBirthday) {
        this.userBirthday = userBirthday;
    }

    /**
     * @return the userBirthday
     */
    public Date getUserBirthday() {
        return userBirthday;
    }
    
}
